<?php

/**
 * @author Thanh Nguyen Dinh <thanhnguyendinh@admicro.vn>
 * @copyright 2013
 */

class News extends MX_Controller
{
    
    public function __construct()
    {
        parent::__construct();
        $this->load->library('Admin_Layout');
        $this->load->library('Minifier');
        $this->load->library('Myvietstring');
        $this->load->library('Myimage');
		$this->load->model("news/admin_news_model");		
    }

    public function index($page='')
    {    	    	    	
		$this->mycommon->authAdmin();
        $this->admin_layout->_loadHeader("");
        $this->admin_layout->_loadLeftMenu();
		$data = array();		
		$page = ($page != '') ? intval($page) : 1;
        $this->load->library('pagination');         
        $config['base_url'] = site_url('admin/news/index');
        $config['total_rows'] = $this->admin_news_model->get_count_news(1);
        $config['per_page'] = 10;
        $config['use_page_numbers'] = TRUE;
        $config['first_link'] = '&lsaquo; Trang Ä‘áº§u';
        $config['last_link'] = 'Trang cuá»‘i &lsaquo;';
        $config['cur_page'] = $page;
        $config['uri_segment'] = 4;        
        $this->pagination->initialize($config);
        $start = ($page - 1) * $config['per_page'];
        $data['pagination'] = $this->pagination->create_links();
        $data['cur_page'] = $page;
        $data['total_page'] = $this->pagination->num_links;  
        $data['infos'] = $this->admin_news_model->get_all_news($start, $config['per_page'],1,null);				  
		if($this->input->post())
		{
			$option = $this->input->post('applyfield');
			if($option == 1)
			{
				$check_items = $this->input->post('check_item');				
				if($check_items){
					foreach($check_items as $check_item)
					{						
						$this->delete($check_item);
					}	
				}				
			}		
		}		
		         
        $this->load->view("news/news_view",$data);
        $this->admin_layout->_loadFooter();
    }
    
    public function update()
    {    	
    	$this->mycommon->authAdmin();
    	$data = array();
    	$data['error'] = "";
    	$info = $this->input->post();
    	if($info['status'] != 0)
    		$info['status'] = 1;    	
    	$result = $this->admin_news_model->update_news($info);
    	if(!$result){
    		 $data['error'] = 1;    		 
    	}    	    		        	
    	echo json_encode($data);
    }
    
    public function delete($id)
    {
    	$this->mycommon->authAdmin();
    	$result = $this->admin_news_model->delete_news($id);
    	if($result)
    		redirect(site_url('admin/news'));	    	
    }
    
    public function add()
    {
    	$this->mycommon->authAdmin();
    	$data = array();
        $data['error'] = '';        
        $this->minifier->AddJsNoPack('jquery.validate');
        $this->minifier->AddJsNoPack('tiny_mce/tiny_mce');
    	$this->admin_layout->_loadHeader("");  
    	$this->admin_layout->_loadLeftMenu();	   
		if($this->input->post())
		{
			$title = $this->input->post('title',true);
			$description = $this->input->post('description',true);
			$content = $this->input->post('content');
			$status = $this->input->post('status');
			if($status != 1)
				$status = 0;									
			if(strlen($title) > 50 || strlen($title) < 10 || strlen($description) < 100)
				$data['error'] = 1;				
			else{
				$filename = $_FILES['upload']['name'];
            	$url_image = "";
            	if($filename != ""){
            		$type = $_FILES['upload']['type'];
            		if( $type == 'image/jpeg' || $type == 'image/png' || $type == 'image/pjpeg' || $type == 'image/gif' && $_FILES['upload']['size'] < (1024 * 3)){             
	            		$pos = strrpos($filename, '.');
				        $name = substr($filename, 0, $pos);
				        $name = strtolower(str_replace(' ', '-', $this->myvietstring->removeVietChars($name)));
				        $name = $this->myvietstring->removeInvalidCharacter($name);
				        $name = strlen(strlen($name) > 10) ? substr($name, 0, 10) : $name;
				        $name.= '-' . time();
				        $name_thumb = 'thumb_' . $name;
				        $fileParts = pathinfo($_FILES['upload']['name']);
				        $targetFile = $name .".".$fileParts['extension'];
				        $this->myimage->resizeFromWidthAndHeight($_FILES['upload']['tmp_name'], 200, 200, "uploads/images/" . $name_thumb.'.'.$fileParts['extension']);			            	
	            		$check = move_uploaded_file($_FILES['upload']['tmp_name'],"uploads/images/" . $targetFile);            			            		
	            		$url_image = "uploads/images/".$name_thumb.'.'.$fileParts['extension'];
	            		if($check){
	            			$info = array(  
	            				'title'=>$title,
								'description'=>$description,
								'content'=>$content,
								'image'=>$url_image,
	            				'createdate'=>date("Y-m-d H:i:s"),
	            				'modifydate'=>date("Y-m-d H:i:s"),	
								'type'=>1,
								'status'=>$status	
							);
							$news_id = $this->admin_news_model->add_news($info);
							if(!$news_id)
								$data['error'] = 1;
							else 
								redirect(site_url('admin/news/edit/'.$news_id));
				         }
				         else{
				         	$data['error'] = 1;
				         }
			        }            			
            	}				
			}			 		
		}
		$data['frmToken'] = uniqid();
        $this->session->set_userdata('frmToken',$data['frmToken']);
		$this->load->view("news/add_view",$data);	
		$this->admin_layout->_loadFooter();
    	    	
    }
    
    public function edit($id)
    {
    	$this->mycommon->authAdmin();
    	if(!$id || !is_numeric($id)){
    		redirect(site_url('admin'));
    	}
    	$data = array();
        $data['error'] = '';
        $data['success'] = '';
        $this->minifier->AddJsNoPack('jquery.validate');
        $this->minifier->AddJsNoPack('tiny_mce/tiny_mce');
    	$this->admin_layout->_loadHeader(""); 
    	$this->admin_layout->_loadLeftMenu();  	  	  
    	if($this->input->post())
		{
			$title = $this->input->post('title',true);
			$description = $this->input->post('description',true);
			$content = $this->input->post('content');
			$status = $this->input->post('status');
			if($status != 1)
				$status = 0;									
			if(strlen($title) > 50 || strlen($title) < 10 || strlen($description) < 100)
				$data['error'] = 1;				
			else{
				$filename = $_FILES['upload']['name'];
            	$url_image = "";
            	if($filename != ""){
            		$type = $_FILES['upload']['type'];
            		if( $type == 'image/jpeg' || $type == 'image/png' || $type == 'image/pjpeg' || $type == 'image/gif' && $_FILES['upload']['size'] < (1024 * 3)){             
	            		$pos = strrpos($filename, '.');
				        $name = substr($filename, 0, $pos);
				        $name = strtolower(str_replace(' ', '-', $this->myvietstring->removeVietChars($name)));
				        $name = $this->myvietstring->removeInvalidCharacter($name);
				        $name = strlen(strlen($name) > 10) ? substr($name, 0, 10) : $name;
				        $name.= '-' . time();
				        $name_thumb = 'thumb_' . $name;
				        $fileParts = pathinfo($_FILES['upload']['name']);
				        $targetFile = $name .".".$fileParts['extension'];
				        $this->myimage->resizeFromWidthAndHeight($_FILES['upload']['tmp_name'], 200, 200, "uploads/images/" . $name_thumb.'.'.$fileParts['extension']);			            	
	            		$check = move_uploaded_file($_FILES['upload']['tmp_name'],"uploads/images/" . $targetFile);            			            		
	            		$url_image = "uploads/images/".$name_thumb.'.'.$fileParts['extension'];
	            		if(!$check)
	            			$data['error'] = "Upload không thành công!";	            			
			        }
			        else{
			        	$data['error'] = "Định dạng của file không được hỗ trợ!";
			        }            			
            	}     
            	if($data['error'] == ""){       	
	            	if($url_image != "")         	
		            	$info = array(  
		            				'id'=>$id,
		            				'title'=>$title,
									'description'=>$description,
									'content'=>$content,
									'image'=>$url_image,	            				
		            				'modifydate'=>date("Y-m-d H:i:s"),									
									'status'=>$status	
								);
					else
						$info = array(  
									'id'=>$id,
		            				'title'=>$title,
									'description'=>$description,
									'content'=>$content,									            				
		            				'modifydate'=>date("Y-m-d H:i:s"),									
									'status'=>$status	
								);
					
					$result = $this->admin_news_model->update_news($info);
					if(!$result)
						$data['error'] = "Cập nhật không thành công!";
					else 
						$data['success'] = "Cập nhật thành công!";
            	}				
			}			 		
		}   
		$data['news'] = $this->admin_news_model->get_news_by_id($id); 	
    	$data['frmToken'] = uniqid();
        $this->session->set_userdata('frmToken',$data['frmToken']);
		$this->load->view("news/edit_view",$data);	
		$this->admin_layout->_loadFooter();    	
    }

}

?>
